import { history } from 'umi';
import React, { useState, useRef, useEffect, forwardRef } from 'react';
import { PageContainer, FooterToolbar, PageHeader } from '@ant-design/pro-layout';
import {
  Button,
  Divider,
  message,
  Input,
  Drawer,
  Table,
  Tabs,
  Card,
  Modal,
  Tag,
  Select,
  Descriptions,
  Spin,
  Popconfirm,
  Popover,
} from 'antd';
import ProTable from '@ant-design/pro-table';
import CopyToClipboard from 'react-copy-to-clipboard';
import { CopyOutlined } from '@ant-design/icons';

import { getImageDetail, getImageVersions, deleteImageVersion } from './service';
import format from '@/utils/format';
import ImageUpload from '../Harbor/components/upload';
import ImagePull from '../Harbor/components/pull';
import ImageServer from '../Harbor/components/server';
import { SORTS } from '@/utils/const';
import { AuthzHOC } from '@apulis/authz';
import { bytesToSize } from '@/utils/utils';

const imageDetail = (props, ref) => {
  const imageId = props.location.query.id;
  const [pageDetail, setPageDetail] = useState({});
  const [loading, setLoading] = useState(false);
  const getCapacity = (capacity) => {
    const c = Number(capacity);
    if (c < 1024) return `${c} KB`;
    let m = Number(parseFloat(c) / 1024).toFixed(1);
    if (m < 1024) return `${m} MB`;
    let g = Number(parseFloat(m) / 1024).toFixed(1);
    if (g < 1024) return `${m} GB`;
    let t = Number(parseFloat(g) / 1024).toFixed(1);
    return `${t} TB`;
  }
  const columns = [
    {
      title: '镜像版本',
      dataIndex: 'imageVersion',
    },
    {
      title: '大小',
      dataIndex: 'imageSize',
      render: (e) => {
        // let c = Number(parseFloat(e) / 1024).toFixed(1);
        // let count = Number(c) < 1024 ? `${c} kb` : `${Number(parseFloat(c) / 1024).toFixed(1)} MB`;
        // return count;
        return bytesToSize(e)
      },
    },
    {
      title: '下载指令',
      dataIndex: 'downloadCommand',
      render: (text) => {
        return (
          <div>
            <Popover content={text}>
              <span className='textEllipsis' style={{width: '300px', display: 'inline-block'}}>
                {text}{' '}
              </span>
            </Popover>
            <CopyToClipboard
              text={text}
              onCopy={() => {
                message.info('复制成功');
              }}
            >
              <CopyOutlined style={{ cursor: 'pointer' }} />
            </CopyToClipboard>
          </div>
        );
      },
    },

    {
      title: '创建时间',
      dataIndex: 'createAt',
      render(text) {
        return format(text);
      },
      sorter: true
    },

    {
      title: '操作',
      render(text, row) {
        return (
          <div>
            <AuthzHOC permission="/apharbor/api/v1/images/imageVersion/{id}" action={['delete']}>
              <Popconfirm
                title="是否确定删除?"
                onConfirm={() => {
                  deleteImageVersion(row.id).then((res) => {
                    if (res.code == 0) {
                      TableRef.current.reload();
                    }
                  });
                }}
                okText="是"
                cancelText="否"
              >
                <span className="ldm l-text-btn danger">删除</span>
              </Popconfirm>
            </AuthzHOC>
          </div>
        );
      },
    },
  ];

  const uploadRef = React.useRef();
  const pullRef = React.useRef();
  const serverRef = React.useRef();
  const TableRef = React.useRef(); // 表格的ref
  const { Item } = Descriptions;

  useEffect(() => {
    getImageDetail(imageId).then((res) => {
      setPageDetail(res.data.image);
    });
  }, []);

  return (
    <div>
      <PageContainer
        onBack={() => {
          history.push('/harbor');
        }}
        title="镜像详情"
      >
        <Card>
          <Spin spinning={loading}>
            <Descriptions title="基础信息" column="12">
              {pageDetail.imageName && (
                <>
                  <Item label="镜像名称">{pageDetail.imageName}</Item>
                  <Item label="所属用户组">{pageDetail.groupName}</Item>
                  <Item label="版本数">{pageDetail.versionCount}</Item>
                  <Item label="创建时间">{format(pageDetail.createAt)}</Item>
                  <Item label="已用空间">{pageDetail.size}</Item>
                  <Item label="下载次数">{pageDetail.pullCount}</Item>
                </>
              )}
            </Descriptions>
          </Spin>
          <Divider />
          <div className="ldm l-title">镜像版本</div>
          {/* 使用left-toobar则无法使用headerTitle,使用l-title代替 */}
          <ProTable
            className="ldm left-toolbar"
            options={false}
            actionRef={TableRef}
            search={false}
            rowKey={(r) => r.id}
            cardProps={{
              bodyStyle: { padding: 0 },
            }}
            request={async (params, sorter, filter) => {
              console.log(sorter);
              const sorterStr = sorter.createAt ? `createAt|${SORTS.get(sorter.createAt)}` : ''
              const res = await getImageVersions({
                pageNum: params.current,
                pageSize: params.pageSize,
                imageId: imageId,
                sort: sorterStr,
              });
              if (res && res.code === 0) {
                return {
                  data: res.data.items,
                  success: true,
                  total: res.data.total,
                };
              }
            }}
            toolBarRender={() => [
              <div>
                <AuthzHOC permission="/apharbor/api/v1/images/image" action={['post']}>
                  <Button
                    type="primary"
                    onClick={() => {
                      uploadRef.current.open({ id: imageId });
                    }}
                    style={{ marginRight: '10px' }}
                  >
                    页面上传
                  </Button>
                  <Button
                    type="primary"
                    onClick={() => {
                      pullRef.current.open({ id: imageId });
                    }}
                    style={{ marginRight: '10px' }}
                  >
                    云端拉取
                  </Button>
                  {/* <Button
                    type="primary"
                    onClick={() => {
                      serverRef.current.open();
                    }}
                    style={{ marginRight: '10px' }}
                  >
                    客户端上传
                  </Button> */}
                </AuthzHOC>
              </div>,
            ]}
            columns={columns}
          />
        </Card>
      </PageContainer>
      <ImageUpload
        userGroup={pageDetail.groupName}
        ref={uploadRef}
        success={() => {
          TableRef.current.reload();
        }}
      />
      <ImagePull
        userGroup={pageDetail.groupName}
        ref={pullRef}
        success={() => {
          TableRef.current.reload();
        }}
      />
      <ImageServer
        ref={serverRef}
        success={() => {
          ref.current.reload();
        }}
      ></ImageServer>
    </div>
  );
};

export default imageDetail;
